﻿using Pb;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;


public class LoginModel : Game
{
    EginMahjong mahjong = EginMahjong.Instance;
    public string ConcentIP = "116.62.190.213";   // 116.62.190.213   // 192.168.1.108测试 //192.168.1.
    public string ConcentPort = "3342";       //3342
    EginUser user = EginUser.Instance;
    EginDN dn = EginDN.Instance;
    EginXTJ xtj = EginXTJ.Instance;
    public GameObject Login;


    //输入框
    public UIInput UserName;
    public UIInput Passward;
   
    //按钮
    public GameObject LoginBtn;
    public GameObject FindPasswordBtn;
    public GameObject RegisterBtn;

    

    //以下四个btn可以改为checkbox
    public GameObject RemberPasswordBtn;
    public GameObject NoRemberPasswordBtn;
    public GameObject AutoLoginBtn;
    public GameObject NoAutoLoginBtn;

    private bool isNotLogin = false;
    private bool RemberPassword = false;
    private bool AutoLogin = false;

    public GameObject Root;


    SoundModel soundModel;
    private void Awake()
    {
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        UIEventListener.Get(LoginBtn).onClick = ButtonClick;
        UIEventListener.Get(RegisterBtn).onClick = ButtonClick;
        UIEventListener.Get(RemberPasswordBtn).onClick = ButtonClick;
        UIEventListener.Get(NoRemberPasswordBtn).onClick = ButtonClick;
        UIEventListener.Get(AutoLoginBtn).onClick = ButtonClick;
        UIEventListener.Get(NoAutoLoginBtn).onClick = ButtonClick;
        UIEventListener.Get(FindPasswordBtn).onClick = ButtonClick;
        soundModel = GameObject.Find("SoundManger").GetComponent<SoundModel>();
    }
    private void Start()
    {
       StartCoroutine(loadScene());

       LoginStatu();
    }

    IEnumerator loadScene()
    {
        StartFunc();
        yield return null;
    }

    protected void StartFunc()
    {
        StartCoroutine(StartGame());
    }
    /// <summary>
    /// 连接服务器
    /// </summary>
    /// <returns></returns>
    protected IEnumerator StartGame()
    {
        SocketConnectInfo connectInfo = SocketConnectInfo.Instance;
        connectInfo.roomHost = ConcentIP; // 116.62.190.213   // 192.168.1.108测试
        connectInfo.roomPort = ConcentPort;
        SocketManager socketManager = SocketManager.Instance;
        yield return socketManager;
        socketManager.ConnectTest(connectInfo);
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;
    }

    IEnumerator StartLoginStatu()
    {
        yield return new WaitForSeconds(3f);
        if (isNotLogin == false)
        {
            LoginEvent();
        }

    }


    /// <summary>
    /// 加载登录信息
    /// </summary>
    private void LoginStatu()
    {
        RemberPassword = (PlayerPrefs.GetInt("RemberPassword") == 1);
        AutoLogin = (PlayerPrefs.GetInt("AutoLogin") == 1);
        if (RemberPassword)
        {
            UserName.value = PlayerPrefs.GetString("EginUsername", "");
            Passward.value = PlayerPrefs.GetString(UserName.value, "");
            RemberPasswordBtn.SetActive(true);
            NoRemberPasswordBtn.SetActive(false);
        }
        else
        {
            RemberPasswordBtn.SetActive(false);
            NoRemberPasswordBtn.SetActive(true);
        }
        if (AutoLogin)
        {
            //切换账号时不要自动登录
            //if (user.SwitchAccount)
            //{

            //}
            //else
            //{
            //    LoginEvent();
            //}

            StartCoroutine(StartLoginStatu());
            AutoLoginBtn.SetActive(true);
            NoAutoLoginBtn.SetActive(false);
        }
        else
        {
            AutoLoginBtn.SetActive(false);
            NoAutoLoginBtn.SetActive(true);
        }
    }
    /// <summary>
    /// 当前界面UI的点击事件
    /// </summary>
    /// <param name="button"></param>
    void ButtonClick(GameObject button)
    {
        if (button.name == "LoginBtn")
        {
            LoginEvent();
        }

        else if (button.name == "RegisterBtn")
        {
            isNotLogin = true;
            AutoLogin = false;
            AutoLoginBtn.SetActive(false);
            NoAutoLoginBtn.SetActive(true);
            GameObject RegisterPanel = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load(HallPrafabPath.Register)));
            //  Register.SetActive(true);
        }
        else if (button.name == "RemberPasswordBtn")
        {
            //不记住密码
            RemberPasswordBtn.SetActive(false);
            NoRemberPasswordBtn.SetActive(true);
            RemberPassword = false;
        }
        else if (button.name == "NoRemberPasswordBtn")
        {
            //记住密码
            NoRemberPasswordBtn.SetActive(false);
            RemberPasswordBtn.SetActive(true);
            RemberPassword = true;
        }
        else if (button.name == "AutoLoginBtn")
        {
            //不自动登录 
            AutoLoginBtn.SetActive(false);
            NoAutoLoginBtn.SetActive(true);
            AutoLogin = false;
            isNotLogin = true;
        }
        else if (button.name == "NoAutoLoginBtn")
        {
            //自动登录
            NoRemberPasswordBtn.SetActive(false);
            RemberPasswordBtn.SetActive(true);
            RemberPassword = true;
            NoAutoLoginBtn.SetActive(false);
            AutoLoginBtn.SetActive(true);
            AutoLogin = true;
        }
        else if (button.name == "Forget_Password_Btn")
        {
            GameObject FindPasswordPanel = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load(HallPrafabPath.Forget_Password_Panel)));
            isNotLogin = true;
            AutoLogin = false;
            AutoLoginBtn.SetActive(false);
            NoAutoLoginBtn.SetActive(true);
        }
        SaveLoginInfo();
    }


    /// <summary>
    /// 分发到场景的接收服务器消息 当前场景为login
    /// </summary>
    /// <param name="data"></param>
    public override void SocketReceiveMessage(byte[] data)
    {
        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(4).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);
        //返回chickin的消息
        if (TempMsgID == MsgId.CheckinResponse)
        {
            Pb.CheckinResponse newpb = Pb.CheckinResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //存储checkin返回消息

            user.ddzRoomList = newpb.DdzRoomList.ToList();
            user.mahjongRoomList = newpb.MahjongRoomList.ToList();
            user.nnRoomList = newpb.NnRoomList.ToList();
            user.pdkRoomList = newpb.RunRoomList.ToList();
            user.xtjRoomList = newpb.PaigowRoomList.ToList();
            //接收到chickin 说明服务器连接成功
            // LoginStatu();  //不自动登录注释掉就可以
        }
        else if (TempMsgID == MsgId.GameRollNoticeBroadcast)  //大厅公告
        {
            Pb.GameRollNoticeBroadcast newpb = Pb.GameRollNoticeBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            EginUser.Instance.NoticePb = newpb.NoticeList.ToList();
            if (newpb.NoticeList.Count > 0)
            {
                EginUser.Instance.haveNotice = true;
            }

            //GameObject Notice = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load("Notice")));
            //NoticeModel noticeModel = Notice.GetComponent<NoticeModel>();
            //Notice.transform.localPosition = new Vector3(-133, 33, 0);
            //noticeModel.NoticePb = newpb.NoticeList.ToList();
        }
        #region  登录
        //处理登录后消息
        else if (TempMsgID == MsgId.LoginResponse)
        {
            Pb.LoginResponse newpb = Pb.LoginResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            print("==========================");
            if (newpb.Status == STATUS.Success)
            {
                user.Uid = newpb.UserInfo.Uid.ToString();
                user.IP = newpb.UserInfo.Ip;
                user.nickname = newpb.UserInfo.Nickname;
                user.coinCount = newpb.UserInfo.BagCoinCount.ToString();
                user.roomCardCount = newpb.UserInfo.RoomCardCount;
                user.sex = newpb.UserInfo.Sex;
                user.avatarId = newpb.UserInfo.AvatarId;
                //user.alipay = newpb.Alipay;
                //user.realName = newpb.Realname;
                user.isAgent = newpb.IsAgent;
                //user.agentUid = newpb.AgentUid;
                Debug.Log("昵称：" + newpb.UserInfo.Nickname + ";" + "金币：" + newpb.UserInfo.BagCoinCount + ";头像：" + newpb.UserInfo.AvatarId);
                Debug.Log("newpb.GameRoomId = " + newpb.GameRoomId);
                user.SignTimes = newpb.SignRewardTimes;
                user.bankCoinCount = newpb.UserInfo.BankCoinCount / 10000;
                print(newpb.SignRewardTimes);
                print("user.SignTimes ====" + user.SignTimes);
                //Application.LoadLevelAsync(ScenePath.Hall);
                //登录成功后要进行重连判断
                #region 麻将存储
                mahjong.nickname = newpb.UserInfo.Nickname;
                mahjong.uid = newpb.UserInfo.Uid;
                mahjong.sex = newpb.UserInfo.Sex;
                mahjong.coinCount = newpb.UserInfo.BagCoinCount;
                mahjong.Score = newpb.UserInfo.Score;
                mahjong.openRoomId = newpb.GameRoomId;
                mahjong.gameRoomId = newpb.GameRoomId;
                // mahjong.win_rate = newpb.UserInfo.GameInfoList[0].WinRate;
                // mahjong.GameType = newpb.UserInfo.GameInfoList[0].GameType.ToString();
                mahjong.seatStatus = newpb.UserInfo.SeatStatus;
                mahjong.Avatar_id = newpb.UserInfo.AvatarId;
                mahjong.IP = newpb.UserInfo.Ip;
                #endregion

                user.gameType = newpb.GameTypeId;

                if (newpb.GameRoomId != 0)
                {
                    Debug.Log("newpb.GameTypeId = " + newpb.GameTypeId);
                    if (newpb.GameTypeId == 101)
                    {
                        EginXTJ.Instance.roomId = newpb.GameRoomId;
                    }
                    reconnect(newpb.GameTypeId);
                    user.gameType = (newpb.GameTypeId);
                   
                }
                else
                {
                    Application.LoadLevelAsync("Hall");//不用异步会卡死 暂时不知道什么原因-------
                }
            }
            else
            {
                user.logMsg = newpb.Msg;
                //LoadModel("LogMsg");
            }
        }
        #endregion

        #region  重连返回消息
        //处理登录后消息
        else if (TempMsgID == MsgId.NnReconnectRoomResponse)
        {
            Pb.NnReconnectRoomResponse newpb = Pb.NnReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            NnReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.DdzReconnectRoomResponse)
        {
            Pb.DdzReconnectRoomResponse newpb = Pb.DdzReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            DdzReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.MahjongReconnectRoomResponse)
        {
            Pb.MahjongReconnectRoomResponse newpb = Pb.MahjongReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            MahjongReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.RunReconnectRoomResponse)
        {
            Pb.RunReconnectRoomResponse newpb = Pb.RunReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            RunReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.Nn100ReconnectResponse)
        {
            Pb.Nn100ReconnectResponse newpb = Pb.Nn100ReconnectResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Nn100ReconnectResponse(newpb);
        }  
        else if (TempMsgID == MsgId.PaiEnterRoundResponse)
        {
            Pb.PaiEnterRoundResponse newpb = Pb.PaiEnterRoundResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            XTJ100ReconnectResponse(newpb);
        }
            
        #endregion

        //注册返回消息
        else if (TempMsgID == MsgId.RegisterResponse)
        {
            Pb.RegisterResponse newpb = Pb.RegisterResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            GameObject RegisterPanel = GameObject.Find("RegisterPanel");

            if (newpb.Status == STATUS.Success)
            {
                Destroy(GameObject.Find("RegisterPanel"),2f);
                user.logMsg = "注册成功";
                if (RegisterPanel)
                {
                    GameObject Set = NGUITools.AddChild(RegisterPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                user.logMsg = "注册成功！";
            }
            else
            {
                user.logMsg = newpb.Msg;
                if (RegisterPanel)
                {
                    GameObject Set = NGUITools.AddChild(RegisterPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                
            }
        }
        // 获取验证码服务器返回的消息
        else if (TempMsgID == MsgId.TelephoneCodeResponse)
        {
            TelephoneCodeResponse newpb = TelephoneCodeResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            GameObject RegisterPanel = GameObject.Find("RegisterPanel");
            GameObject forgetPsdPanel = GameObject.Find("Forget_Password_Panel");
            if (newpb.Status == STATUS.Success)
            {
                user.logMsg = "发送成功，请注意查收";
                if (RegisterPanel)
                {
                    CountDown("yzm2", RegisterPanel);
                    GameObject Set = NGUITools.AddChild(RegisterPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                else if (forgetPsdPanel)
                {
                    CountDown("yzm2", forgetPsdPanel);
                    GameObject Set = NGUITools.AddChild(forgetPsdPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                else
                {
                    GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
                }
            }
            else
            {
                user.logMsg = newpb.Msg;
                if (RegisterPanel)
                {
                    GameObject Set = NGUITools.AddChild(RegisterPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                else if (forgetPsdPanel)
                {
                    GameObject Set = NGUITools.AddChild(forgetPsdPanel, (GameObject)(Resources.Load("LogMsg")));
                }
                else
                {
                    GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
                }
               
            }
        }
        // 找回密码返回的消息
        else if (TempMsgID == MsgId.FindPasswordResponse)
        {
            FindPasswordResponse newpb = FindPasswordResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == STATUS.Success)
            {
                user.logMsg = "修改成功";
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
        }
        //更改头像返回消息
        /*   else if (TempMsgID == MsgId.ModifyAvatarRequest)
           {
               Pb.ModifyAvatarRequest mo = Pb.ModifyAvatarRequest.Parser.ParseFrom(dataConcent);
               Debug.Log("消息ID" + TempMsgID + "消息内容" + mo);
           
           }*/

        //网络异常
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load("NetWorkAbnormal")));
        }
    }


    /// <summary>
    /// 登录事件  给服务器发送登录消息
    /// </summary>
    void LoginEvent()
    {               
        string username = ProtoDataToMsg.stringToUTF8(UserName.value);
        string nickname = null;
        string passwd = ProtoDataToMsg.stringToUTF8(DataSet.StringToMd5(Passward.value));

        string dev_name = SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel);     //SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel)  //ProtoDataToMsg.stringToUTF8("小米");  
        string dev_number = SystemInfo.deviceUniqueIdentifier;
        //string avatar_url=
        isNotLogin = false;
        if (username.Length != 0 && passwd.Length != 0)
        {
            LoginRequest lg = new Pb.LoginRequest { Channel = CHANNEL_TYPE.Telephone, Username = username, Passwd = passwd, DevName = dev_name, DevNumber = dev_number };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.LoginRequest);
            SaveLoginInfo();
        }
        else
        {
            user.logMsg = "账号和密码不能为空";
            GameObject msg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)Resources.Load("LogMsg"));
        }                        
    }

    /// <summary>
    /// 保存登录信息
    /// </summary>
    private void SaveLoginInfo()
    {
        PlayerPrefs.SetString("EginUsername", UserName.value);
        PlayerPrefs.SetString(UserName.value, Passward.value); 
        PlayerPrefs.SetInt("RemberPassword", RemberPassword ? 1 : 0);
        PlayerPrefs.SetInt("AutoLogin", AutoLogin ? 1 : 0);
    }
    /// <summary>
    /// 重连
    /// </summary>
    /// <param name="GameRoomId"></param>
    void reconnect(int GameRoomId)
    {
        if (GameRoomId == 1)
        {
            //发送麻将重连
            MahjongReconnectRoomRequest lg = new Pb.MahjongReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.MahjongReconnectRoomRequest);
        }
        else if (GameRoomId == 2)
        {
            //发送牛牛重连
            NnReconnectRoomRequest lg = new Pb.NnReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.NnReconnectRoomRequest);

        }
        else if (GameRoomId == 3)
        {

            //发送斗地主重连
            DdzReconnectRoomRequest lg = new Pb.DdzReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.DdzReconnectRoomRequest);
        }
        else if (GameRoomId == 4)
        {
            //发送跑得快重连
            RunReconnectRoomRequest lg = new Pb.RunReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.RunReconnectRoomRequest);
            Debug.Log("发送跑得快的重连消息");
        }
        else if (GameRoomId == 100)
        {
            //发送百人牛牛重连
            Nn100ReconnectRequest lg = new Pb.Nn100ReconnectRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.Nn100ReconnectRequest);
            Debug.Log("发送牛牛百人场的重连消息");
        }
        else if(GameRoomId == 101){
            PaiEnterRoundRequest pr = new Pb.PaiEnterRoundRequest { RoundId = EginXTJ.Instance.roomId};
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(pr, MsgId.PaiEnterRoundRequest);
            Debug.Log("发送天九的重连消息");
        }
    }
    /// <summary>
    /// 牛牛重连处理
    /// </summary>
    /// <param name="newpb"></param>
    void NnReconnectRoomResponse(NnReconnectRoomResponse newpb)
    {
        if (newpb.Status == STATUS.Success)
        {
            dn.seatId = newpb.SeatId;
            dn.bankerSid = newpb.BankerSid;
            dn.createrUid = newpb.RoomInfo.CreaterUid;
            dn.roomId = newpb.RoomInfo.RoomId;
            if (newpb.RoomInfo.IsCardRoom)
            {
                user.ControlScene = 1;
            }
            else
            {
                user.ControlScene = 2;
            }
            dn.MaxBankerMultiple = newpb.MaxBankerMultiple;
            dn.MaxBankerMultiple = newpb.MaxPlayerMultiple;
            dn.isReconnect = true;
            user.gameUserInfoList = newpb.UserList.ToList();
            dn.nnReconnectRoomResponse = newpb;

            soundModel.SwitchBgMusic(user.gameType);
            Application.LoadLevelAsync(ScenePath.GameDNPlay);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject logmsg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }
    }
    /// <summary>
    /// 斗地主重连消息
    /// </summary>
    /// <param name="newpb"></param>
    void DdzReconnectRoomResponse(DdzReconnectRoomResponse newpb)
    {
        EginDDZ ddz = EginDDZ.Instance;
        // EginUser user = EginUser.Instance;
        if (newpb.Status == STATUS.Success)
            if (newpb.Status == STATUS.Success)
            {
                ddz.roomStatus = newpb.RoomInfo.RoomStatus;
                ddz.roomId = newpb.RoomInfo.RoomId;
                ddz.seatId = newpb.SeatId;
                ddz.SortSeatId();
                ddz.lordSid = newpb.LordSid;
                ddz.nextSid = newpb.TurnSid;
                ddz.createrUid = newpb.RoomInfo.CreaterUid;

                user.gameUserInfoList = newpb.UserInfoList.ToList();
                if (newpb.RoomInfo.IsCardRoom)
                {
                    user.ControlScene = 1;
                }
                else
                {
                    user.ControlScene = 2;
                }
                Debug.Log(newpb.RoomInfo.IsCardRoom+""+ user.ControlScene);
                ddz.ddzReconnectRoomResponse = newpb;
                ddz.isReconnect = true;
                soundModel.SwitchBgMusic(user.gameType);
                Application.LoadLevelAsync(ScenePath.GameDDZPlay);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject logmsg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
            }
    }
    /// <summary>
    /// 麻将重连
    /// </summary>
    /// <param name="newpb"></param>
    void MahjongReconnectRoomResponse(MahjongReconnectRoomResponse newpb)
    {
        
        if (newpb.RoomInfo.IsCardRoom)
        {
            user.ControlScene = 1;
        }
        else
        {
            user.ControlScene = 2;
        }
        if (newpb.RoomInfo.RoomStatus == ROOM_STATUS.Gaming)
        {
            mahjong.gameRecent = true;
        }
        else
        {
            mahjong.gameRecent = false;
        }
        //mahjong.roomTypeId = newpb.RoomInfo.RoomTypeId;
        mahjong.CteatrUid = newpb.RoomInfo.CreaterUid;
        mahjong.roomID = newpb.RoomInfo.RoomId;
        mahjong.baseScore = newpb.RoomInfo.BaseScore;
        mahjong.roomStatus = newpb.RoomInfo.RoomStatus;
        mahjong.currentRound = newpb.RoomInfo.CurrentRound;
        mahjong.CardList = newpb.CardList.ToList();
        mahjong.turnSid = newpb.TurnSid;
        mahjong.nextSid = newpb.TurnSid;
        mahjong.seatID = newpb.SeatId;

        mahjong.remainCount = newpb.RemainCount;
        mahjong.handCard = newpb.HandCard;
        mahjong.tableCard = newpb.TableCard;
        mahjong.bankerSid = newpb.BankerSid;
        mahjong.LastBankSid = newpb.BankerSid;            //一定要在重连也存储否则会显示两个庄
        mahjong.isSpecialPhases2 = newpb.IsSpecialPhases2;

        mahjong.LastSeatID = newpb.LastSid;   //给cardmodel用
        //user.uid=newpb.UserInfoList.
        //存储其他玩家信息

        mahjong.tingCards = newpb.ReadyCards.ToList();
        mahjong.Otheruid = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Uid);
        mahjong.OtherSeatId = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.SeatId);
        mahjong.OtherSeatStatus = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.SeatStatus);
        mahjong.OtherSex = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Sex);
        mahjong.OtherIP = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Ip);
        mahjong.OtherCoinCount = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.BagCoinCount);
        mahjong.OtherScore = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Score);
        mahjong.OtherNickName = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Nickname);
        mahjong.OtherAvatarid = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.AvatarId);
        mahjong.OtherOutCardList = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.OutCardList.ToList());
        mahjong.mahjongDoneSpecialCard = newpb.SpecialDoneList.ToList();
        mahjong.OverRecordList = newpb.ScoreList.ToDictionary(t => t.RoundId, t => t.ScoreRoundList.ToList());  //重连后存储玩家的游戏结束分数     
        mahjong.TotalScore = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Score);
        //Debug.Log("存储其他玩家信息" + user.OtherCoinCount[1]);

        //user.gameUserInfoList = newpb.UserInfoList.ToList();
        if (newpb.SpecialListReady.Count != 0)
        {
            mahjong.mahjongSpecialCardItem = newpb.SpecialListReady.ToList();
        }
        if (newpb.SpecialSid > 0)
        {
            mahjong.nextSid = newpb.SpecialSid;
            mahjong.turnSid = newpb.SpecialSid;
        }

        user.gameUserInfoList = newpb.UserInfoList.ToList();
        Application.LoadLevel("GameMahjongPlay");
    }


    /// <summary>
    /// 跑得快重连处理
    /// </summary>
    /// <param name="newpb"></param>
    void RunReconnectRoomResponse(RunReconnectRoomResponse newpb)
    {
        if (newpb.Status == STATUS.Success)
        {
            EginPDK pdk = EginPDK.Instance;
            pdk.createrUid = newpb.RoomInfo.CreaterUid;
            //pdk.bankerSid = newpb.BankerSid;
            pdk.roomId = newpb.RoomInfo.RoomId;
            pdk.currentRound = newpb.RoomInfo.CurrentRound;
            pdk.baseScore = newpb.RoomInfo.BaseScore;
            pdk.totalRound = newpb.RoomInfo.TotalRound;
            pdk.roomStatus = newpb.RoomInfo.RoomStatus;
            user.gameUserInfoList = newpb.UserInfoList.ToList();
            Debug.Log("房间内有" + user.gameUserInfoList.Count + "个玩家");

            //确定重连的玩家在房间中的位置
            int uid = int.Parse(user.Uid);
            for (int i = 0; i < newpb.UserInfoList.Count; i++)
            {

                if (uid == newpb.UserInfoList[i].Uid)
                {
                    pdk.seatId = newpb.UserInfoList[i].SeatId;
                    Debug.Log("我的seatId = " + newpb.UserInfoList[i].SeatId);
                }
            }

            //判定是不是好友场
            if (newpb.RoomInfo.IsCardRoom)
            {
                user.ControlScene = 1;
                pdk.isCardRoom = true;
            }
            else if(newpb.RoomInfo.IsCardRoom == false && newpb.RoomInfo.TotalRound > 0 ){
                user.ControlScene = 1;
                pdk.isCardRoom = false;
            }
            else
            {
                user.ControlScene = 2;
            }

            pdk.isReconnect = true;
            pdk.runReconnectRoomResponse = newpb;
            soundModel.SwitchBgMusic(user.gameType);
            Application.LoadLevelAsync(ScenePath.GamePDKPlay);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }
    }

    /// <summary>
    /// 百人牛牛重连
    /// </summary>
    /// <param name="newpb"></param>
    void Nn100ReconnectResponse(Nn100ReconnectResponse newpb)
    {
        if(newpb.Status == STATUS.Success){
            
            dn.bankerInfo= newpb.BankerUserInfo;
            dn.chairUserList = newpb.ChairUserList.ToList();
            dn.chipInfo = newpb.ChipInfo;                      
            dn.isReconnect = true;
            user.gameUserInfoList = newpb.UserInfoList.ToList();
            dn.nn100ReconnectResponse = newpb;
            Debug.Log(user.gameType);
            soundModel.SwitchBgMusic(2);
            Application.LoadLevelAsync(ScenePath.GameDNPlay100);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }

    }


    /// <summary>
    /// 天九重连
    /// </summary>
    /// <param name="newpb"></param>
    void XTJ100ReconnectResponse(PaiEnterRoundResponse newpb)
    {
        if (newpb.Status == (int)STATUS.Success)
        {
            xtj.newpb = newpb;
            xtj.playersList = newpb.Round.PlayerInfo.ToList();
            xtj.roomStatus = newpb.Round.Status;
            xtj.currentRound = newpb.Round.Total;
            xtj.roomId = newpb.Round.RoundNumber;
            xtj.roundId = newpb.Round.Id;
            Debug.Log("房间ID：" + newpb.Round.RoundNumber);
            xtj.level = newpb.Round.Level;
            Debug.Log("房间Level：" + newpb.Round.Level);
            xtj.roundType = newpb.Round.RoundType;
            xtj.chipList = newpb.Round.ChipLevels.ToList();
            xtj.cardHistory = newpb.Round.CardHistory.ToList();
            xtj.roundCardNum = xtj.cardHistory.Count / 8;
            xtj.roundNum = newpb.Round.Total;
            xtj.playersNum = newpb.Round.OnlineNumber;
            xtj.roundType = newpb.Round.RoundType;
            xtj.createrUid = newpb.Round.CreatorId;
            xtj.bankerId = newpb.Round.MasterInfo.Id;
            soundModel.SwitchBgMusic(5);

            xtj.bankerInfo = newpb.Round.MasterInfo;
            if (newpb.Round.RoundType == 1)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJ);
            }
            else if (newpb.Round.RoundType == 3)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJOfFriend);
            }
            else if (newpb.Round.RoundType == 4)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJ100);
            }
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }

    }



    /// <summary>
    /// 倒计时
    /// </summary>
    /// <param name="time"></param>
    /// <param name="name"></param>
    void CountDown(string name,GameObject obj)
    {
        //sprite.spriteName = name;
        RegisterModel registerModel = obj.GetComponent<RegisterModel>();
        ForgetPsdModel forgetPsdModel = obj.GetComponent<ForgetPsdModel>();
        if (registerModel)
        {
            UISprite sprite = registerModel.sprite;
            UILabel label = registerModel.label;
            GameObject VerificationCodeBtn = registerModel.VerificationCodeBtn;
            if (sprite)
            {
                sprite.spriteName = name;
            }
            if (label)
            {
                label.gameObject.SetActive(true);
            }
            if (VerificationCodeBtn)
            {
                VerificationCodeBtn.GetComponent<BoxCollider>().enabled = false;
            }          
            StartCoroutine(reduceTime(60, obj));
        }
        if (forgetPsdModel)
        {
            UISprite sprite = forgetPsdModel.sprite;
            UILabel label = forgetPsdModel.label;
            GameObject VerificationCodeBtn = forgetPsdModel.VerificationCodeBtn;
            if (sprite)
            {
                sprite.spriteName = name;
            }
            if (label)
            {
                label.gameObject.SetActive(true);
            }
            if (VerificationCodeBtn)
            {
                VerificationCodeBtn.GetComponent<BoxCollider>().enabled = false;
            }
            StartCoroutine(reduceTime(60, obj));
        }
    }
    IEnumerator reduceTime(int time ,GameObject Obj)
    {
        RegisterModel registerModel = Obj.GetComponent<RegisterModel>();
        ForgetPsdModel forgetPsdModel = Obj.GetComponent<ForgetPsdModel>();
        
        if (registerModel)
        {
            UILabel label = registerModel.label;
            label.text = time.ToString();
            while (time > 0)
            {
                yield return new WaitForSeconds(1);
                time--;
                if (time <= 0)
                {
                    asd(Obj);
                    yield break;
                }
                if (label)
                {
                    label.text = time.ToString();
                }
            }
        }
        if (forgetPsdModel)
        {
            UILabel label = forgetPsdModel.label;
            label.text = time.ToString();
            while (time > 0)
            {
                yield return new WaitForSeconds(1);
                time--;
                if (time <= 0)
                {
                    asd(Obj);
                    yield break;
                }
                if (label)
                {
                    label.text = time.ToString();
                }
            }
        }
       
        
    }
    void asd(GameObject Obj)
    {
        RegisterModel registerModel = Obj.GetComponent<RegisterModel>();
        ForgetPsdModel forgetPsdModel = Obj.GetComponent<ForgetPsdModel>();
        if (registerModel)
        {
            GameObject VerificationCodeBtn = registerModel.VerificationCodeBtn;
            VerificationCodeBtn.GetComponent<BoxCollider>().enabled = true;

            UISprite sprite = registerModel.sprite;
            sprite.spriteName = "yzm1";
        }
        if (forgetPsdModel)
        {
            GameObject VerificationCodeBtn = forgetPsdModel.VerificationCodeBtn;
            VerificationCodeBtn.GetComponent<BoxCollider>().enabled = true;

            UISprite sprite = forgetPsdModel.sprite;
            sprite.spriteName = "yzm1";
        }
    }
}
